﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BoriPeter.NutritionManager.WinFormsClient
{
    public partial class MainForm : Form
    {
        #region private variables
        private decimal SumCalcium = 0;
        private decimal SumCalories = 0;
        private decimal SumCarbohydrate = 0;
        private decimal SumCholesterol = 0;
        private decimal SumFat = 0;
        private decimal SumIron = 0;
        private decimal SumProtein = 0;
        private decimal SumSugar = 0;
        private decimal SumVitaminA = 0;
        private decimal SumVitaminC = 0;
        #endregion

        public MainForm()
        {
            InitializeComponent();
            cbMeal.Items.Add("breakfast");
            cbMeal.Items.Add("lunch");
            cbMeal.Items.Add("dinner");
            cbMeal.Items.Add("other");
        }

        private void foodsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.foodsBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.nutritionManagementDataSet);

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'nutritionManagementDataSet.FoodEntry' table. You can move, or remove it, as needed.
            //this.foodEntryTableAdapter.Fill(this.nutritionManagementDataSet.FoodEntry);
            // TODO: This line of code loads data into the 'nutritionManagementDataSet.FoodEntryView' table. You can move, or remove it, as needed.
            this.foodEntryViewTableAdapter.FillByDate(this.nutritionManagementDataSet.FoodEntryView, dateTimePicker1.Value);
            // TODO: This line of code loads data into the 'nutritionManagementDataSet.Foods' table. You can move, or remove it, as needed.
            this.foodsTableAdapter.Fill(this.nutritionManagementDataSet.Foods);

            this.foodsTableAdapter1.Fill(this.nutritionManagementDataSet.Foods);

            this.foodEntryTableAdapter1.Fill(this.nutritionManagementDataSet.FoodEntry);

            RecalculateDailySummary();
        }

        #region Add new food
        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            if (CheckValueOfTextBoxes())
            {
                this.foodsTableAdapter.Insert(
                     tbNewFoodName.Text,
                     Decimal.Parse(tbNewCalories.Text),
                     Decimal.Parse(tbNewCarbohydrate.Text),
                     Decimal.Parse(tbNewProtein.Text),
                     Decimal.Parse(tbNewFat.Text),
                     Decimal.Parse(tbNewCholesterol.Text),
                     Decimal.Parse(tbNewSugar.Text),
                     Decimal.Parse(tbNewVitaminA.Text),
                     Decimal.Parse(tbNewVitaminC.Text),
                     Decimal.Parse(tbNewCalcium.Text),
                     Decimal.Parse(tbNewIron.Text)
                );

                tbNewFoodName.Text = "";
                tbNewCalories.Text = "";
                tbNewCarbohydrate.Text = "";
                tbNewProtein.Text = "";
                tbNewFat.Text = "";
                tbNewCholesterol.Text = "";
                tbNewSugar.Text = "";
                tbNewVitaminA.Text = "";
                tbNewVitaminC.Text = "";
                tbNewCalcium.Text = "";
                tbNewIron.Text = "";
            }

            foodsTableAdapter.Fill(this.nutritionManagementDataSet.Foods);
            foodsDataGridView.Update();
        }

        #region CheckValueOfTextBoxes
        private bool CheckValueOfTextBoxes()
        {
            string message = "";
            Color okColor = Color.White;
            Color notOkColor = Color.Yellow;
            Boolean retval = true;
            Decimal x;
            if (tbNewFoodName.Text == "")
            {
                message += "\n - Food Name";
                tbNewFoodName.BackColor = notOkColor;
                retval = false;
            }
            else tbNewFoodName.BackColor = okColor;
            
            if (!Decimal.TryParse(tbNewCalories.Text, out x))
            {
                message += "\n - Calories";
                retval = false;
                tbNewCalories.BackColor = notOkColor;
            } else tbNewCalories.BackColor  = okColor;


            if (!Decimal.TryParse(tbNewCarbohydrate.Text, out x))
            {
                message += "\n - Carbohydrate";
                retval = false;
                tbNewCarbohydrate.BackColor = notOkColor;
            }
            else tbNewCarbohydrate.BackColor = okColor;

            if (!Decimal.TryParse(tbNewProtein.Text, out x))
            {
                message += "\n - Protein";
                retval = false;
                tbNewProtein.BackColor = notOkColor;
            }
            else tbNewProtein.BackColor = okColor;

            if (!Decimal.TryParse(tbNewFat.Text, out x))
            {
                message += "\n - Fat ";
                retval = false;
                tbNewFat.BackColor = notOkColor;
            }
            else tbNewFat.BackColor = okColor;

            if (!Decimal.TryParse(tbNewCholesterol.Text, out x))
            {
                message += "\n - Cholesterol ";
                retval = false;
                tbNewCholesterol.BackColor = notOkColor;
            }
            else tbNewCholesterol.BackColor = okColor;

            if (!Decimal.TryParse(tbNewProtein.Text, out x))
            {
                message += "\n - Protein";
                retval = false;
                tbNewProtein.BackColor = notOkColor;
            }
            else tbNewProtein.BackColor = okColor;

            if (!Decimal.TryParse(tbNewSugar.Text, out x))
            {
                message += "\n - Sugar";
                retval = false;
                tbNewSugar.BackColor = notOkColor;
            }
            else tbNewSugar.BackColor = okColor;

            if (!Decimal.TryParse(tbNewVitaminA.Text, out x))
            {
                message += "\n - Vitamin A";
                retval = false;
                tbNewVitaminA.BackColor = notOkColor;
            }
            else tbNewVitaminA.BackColor = okColor;

            if (!Decimal.TryParse(tbNewVitaminC.Text, out x))
            {
                message += "\n - Vitamin C";
                retval = false;
                tbNewVitaminC.BackColor = notOkColor;
            }
            else tbNewVitaminC.BackColor = okColor;

            if (!Decimal.TryParse(tbNewCalcium.Text, out x))
            {
                message += "\n - Calcium";
                retval = false;
                tbNewCalcium.BackColor = notOkColor;
            }
            else tbNewCalcium.BackColor = okColor;

            if (!Decimal.TryParse(tbNewIron.Text, out x))
            {
                message += "\n - Iron";
                retval = false;
                tbNewIron.BackColor = notOkColor;
            }
            else tbNewIron.BackColor = okColor;

            if (message != "") MessageBox.Show("Please enter: " + message + " !");

            return retval;
        }
        #endregion

        #endregion

        #region  Export to XML
        private void exportToXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var FD = new System.Windows.Forms.SaveFileDialog();
            FD.Filter = "XML file|*.xml";
            FD.ShowDialog();

            if (FD.FileName != "")
            {
                var foods = new FoodsModel();
                foods.FoodsList = new List<FoodModel>();
                foreach (var row in foodsTableAdapter.GetData())
                {
                    var food = new FoodModel()
                    {
                        FoodName = row.FoodName,
                        Calories = row.Calories,
                        Carbohydrate = row.Carbohydrate,
                        Protein = row.Protein,
                        Fat = row.Fat,
                        Cholesterol = row.Cholesterol,
                        Sugar = row.Sugar,
                        VitaminA = row.VitaminA,
                        VitaminC = row.VitaminC,
                        Calcium = row.Calcium,
                        Iron = row.Iron
                    };
                    foods.FoodsList.Add(food);
                }
                WriteXML(foods,FD.FileName);
            }
        }

        private void WriteXML(FoodsModel foods, string fileName)
        {
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(FoodsModel));

            System.IO.StreamWriter file = new System.IO.StreamWriter(fileName);
            writer.Serialize(file, foods);
            file.Close();
        }
        #endregion

        #region Import from XML
        private void importFromXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var FD = new System.Windows.Forms.OpenFileDialog();
            if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileToOpen = FD.FileName;

                FoodsModel foods = ReadXML(fileToOpen);

                foreach (var item in foods.FoodsList)
                {
                    NutritionManagementDataSet.FoodsRow newRow;
                    newRow = this.nutritionManagementDataSet.Foods.NewFoodsRow();
                    newRow.Calcium = item.Calcium;
                    newRow.Calories = item.Calories;
                    newRow.Carbohydrate = item.Carbohydrate;
                    newRow.Cholesterol = item.Cholesterol;
                    newRow.Fat = item.Fat;
                    newRow.FoodName = item.FoodName;
                    newRow.Iron = item.Iron;
                    newRow.Sugar = item.Sugar;
                    newRow.VitaminA = item.VitaminA;
                    newRow.VitaminC = item.VitaminC;

                    this.nutritionManagementDataSet.Foods.Rows.Add(newRow);
                }
                foodsTableAdapter.Update(this.nutritionManagementDataSet.Foods);

                foodsDataGridView.Update();
            }
        }
        private FoodsModel ReadXML(string fileName)
        {
            System.Xml.Serialization.XmlSerializer reader =
                new System.Xml.Serialization.XmlSerializer(typeof(FoodsModel));

            System.IO.StreamReader file = new System.IO.StreamReader(fileName);

            FoodsModel foodsModel = (FoodsModel)reader.Deserialize(file);
            file.Close();

            return foodsModel;
        }
        #endregion

        private void fillByToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.foodEntryViewTableAdapter.FillBy(this.nutritionManagementDataSet.FoodEntryView);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            this.foodEntryViewTableAdapter.FillByDate(this.nutritionManagementDataSet.FoodEntryView, dateTimePicker1.Value);
            RecalculateDailySummary();
        }

        #region AddFoodEntry Click
        private void btnAdd_Click(object sender, EventArgs e)
        {
            NutritionManagementDataSet.FoodEntryRow newFoodEntry;
            newFoodEntry = this.nutritionManagementDataSet.FoodEntry.NewFoodEntryRow();
            newFoodEntry.EntryDate = dateTimePicker1.Value;
            newFoodEntry.IdFood = (int)foodNameComboBox.SelectedValue;
            newFoodEntry.Meal = (string)cbMeal.SelectedItem;
            newFoodEntry.NumberOfUnits = decimal.Parse(tbNumberOfUnits.Text);

            this.nutritionManagementDataSet.FoodEntry.Rows.Add(newFoodEntry);
            this.foodEntryTableAdapter1.Update(this.nutritionManagementDataSet);
            this.foodEntryViewTableAdapter.FillByDate(this.nutritionManagementDataSet.FoodEntryView, dateTimePicker1.Value);
            foodEntryViewDataGridView.Update();

            RecalculateDailySummary();
        }
        #endregion

        #region RecalculateDailySummary
        private void RecalculateDailySummary()
        {
            decimal calcium = 0;
            decimal calories = 0;
            decimal carbohydrate = 0;
            decimal cholesterol = 0;
            decimal fat = 0;
            decimal iron = 0;
            decimal protein = 0;
            decimal sugar = 0;
            decimal vitaminA = 0;
            decimal vitaminC = 0;
            foreach (var item in this.nutritionManagementDataSet.FoodEntryView.Rows)
            {
                NutritionManagementDataSet.FoodEntryViewRow row = (NutritionManagementDataSet.FoodEntryViewRow)item;
                calcium += (row.Calcium * row.NumberOfUnits);
                calories += (row.Calories * row.NumberOfUnits);
                carbohydrate += (row.Carbohydrate * row.NumberOfUnits);
                cholesterol += (row.Cholesterol * row.NumberOfUnits);
                fat += (row.Fat * row.NumberOfUnits);
                iron += (row.Iron * row.NumberOfUnits);
                protein += (row.Protein * row.NumberOfUnits);
                sugar += (row.Sugar * row.NumberOfUnits);
                vitaminA += (row.VitaminA * row.NumberOfUnits);
                vitaminC += (row.VitaminC * row.NumberOfUnits);
            }
            SumCalcium = calcium;
            SumCalories = calories;
            SumCarbohydrate = carbohydrate;
            SumCholesterol = cholesterol;
            SumFat = fat;
            SumIron = iron;
            SumProtein = protein;
            SumSugar = sugar;
            SumVitaminA = vitaminA;
            SumVitaminC = vitaminC;

            tbSumCalcium.Text = calcium.ToString();
            tbSumCalories.Text = calories.ToString();
            tbSumCarbohydrate.Text = carbohydrate.ToString();
            tbSumCholesterol.Text = cholesterol.ToString();
            tbSumFat.Text = fat.ToString();
            tbSumIron.Text = iron.ToString();
            tbSumProtein.Text = protein.ToString();
            tbSumSugar.Text = sugar.ToString();
            tbSumVitaminA.Text = vitaminA.ToString();
            tbSumVitaminC.Text = vitaminC.ToString();
        }
        #endregion

        #region exportDiaryToExcel

        private void exportDiaryToExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var FD = new System.Windows.Forms.SaveFileDialog();
            FD.Filter = "Excel 95/97|*.xls|Excel 2003|*.xlsx";
            FD.ShowDialog();

            if (FD.FileName != "")
            {
                int row = 1;

                var excelApp = new Microsoft.Office.Interop.Excel.Application();

                excelApp.Visible = true;

                excelApp.Workbooks.Add();

                Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;

                // Food diary label
                workSheet.Cells[row, 1] = "Food diary";
                workSheet.Range[workSheet.Cells[row, 1], workSheet.Cells[1, 2]].Font.Bold = true;
                workSheet.Range[workSheet.Cells[row, 1], workSheet.Cells[1, 2]].Font.Size = 20;
                workSheet.Range[workSheet.Cells[row, 1], workSheet.Cells[1, 2]].Merge();
                row++;

                workSheet.Cells[row, 1] = "Date:";
                workSheet.Cells[row, 2] = dateTimePicker1.Text.ToString();
                row+=2;

                workSheet.Cells[row, 1] = "meal";
                workSheet.Cells[row, 2] = "name";
                workSheet.Cells[row, 3] = "calcium";
                workSheet.Cells[row, 4] = "calories";
                workSheet.Cells[row, 5] = "carbohydrate";
                workSheet.Cells[row, 6] = "cholesterol";
                workSheet.Cells[row, 7] = "fat";
                workSheet.Cells[row, 8] = "iron";
                workSheet.Cells[row, 9] = "protein";
                workSheet.Cells[row, 10] = "sugar";
                workSheet.Cells[row, 11] = "vitaminA";
                workSheet.Cells[row, 12] = "vitaminC";
                row++;

                foreach (var item in this.nutritionManagementDataSet.FoodEntryView.Rows)
                {
                    NutritionManagementDataSet.FoodEntryViewRow dataRow = (NutritionManagementDataSet.FoodEntryViewRow)item;
                    workSheet.Cells[row, 1] = dataRow.Meal;
                    workSheet.Cells[row, 2] = dataRow.FoodName;
                    workSheet.Cells[row, 3] = dataRow.Calcium * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 4] = dataRow.Calories * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 5] = dataRow.Carbohydrate * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 6] = dataRow.Cholesterol * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 7] = dataRow.Fat * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 8] = dataRow.Iron * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 9] = dataRow.Protein * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 10] = dataRow.Sugar * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 11] = dataRow.VitaminA * dataRow.NumberOfUnits;
                    workSheet.Cells[row, 12] = dataRow.VitaminC * dataRow.NumberOfUnits;
                    row++;
                }
                RecalculateDailySummary();
                workSheet.Cells[row, 2] = "TOTAL:";
                workSheet.Cells[row, 3] = SumCalcium;
                workSheet.Cells[row, 4] = SumCalories;
                workSheet.Cells[row, 5] = SumCarbohydrate;
                workSheet.Cells[row, 6] = SumCholesterol;
                workSheet.Cells[row, 7] = SumFat;
                workSheet.Cells[row, 8] = SumIron;
                workSheet.Cells[row, 9] = SumProtein;
                workSheet.Cells[row, 10] = SumSugar;
                workSheet.Cells[row, 11] = SumVitaminA;
                workSheet.Cells[row, 12] = SumVitaminC;

                // Write to file
                workSheet.SaveAs(FD.FileName);

                excelApp.Quit();
            }

        }
        #endregion


        private void englishToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
            var lang = new CultureInfo("en");
            ComponentResourceManager resources = new ComponentResourceManager(typeof(MainForm));
            ApplyResourceToControl(resources, this, lang);
            resources.ApplyResources(this, "$this",lang);
        }

        private void hungarianToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("hu");
            var lang = new CultureInfo("hu");
            ComponentResourceManager resources = new ComponentResourceManager(typeof(MainForm));
            ApplyResourceToControl(resources, this, lang);
            resources.ApplyResources(this, "$this",lang);
        }

        private void ApplyResourceToControl(ComponentResourceManager resources, Control control, CultureInfo lang)
        {
            foreach (Control cont in control.Controls)
            {
                ApplyResourceToControl(resources, cont, lang);  
                resources.ApplyResources(cont, cont.Name, lang);

                DataGridView dg = cont as DataGridView;
                if (dg != null)
                {
                    foreach (DataGridViewColumn col in dg.Columns)
                    {
                        resources.ApplyResources(col, col.Name, lang);
                    }
                }
            }
        }
    }
}
